
package com.ropzsu.scalaWeb.util;

import java.io._

class HttpRequest  {
  
  def headerResponse(status: String, length: long, contentType: String): String =  {
<header>HTTP/1.0 {status}
Server: ScalaServer/0.1
Content-type: {contentType}
Content-length: {length}
</header>.text.replace("\n", "\r\n");
  }

  def headerPart(is: InputStream): String = {
    val ris = new java.io.InputStreamReader(is)
    var sb = new java.lang.StringBuffer(8192)
    var buf = new Array[Char](1024)
    var n = ris.read(buf)
    while(n > 0 ) {
      sb.append(buf, 0, n)
      if (sb.indexOf("\r\n\r\n") >= 0) return new String(sb)
      n = ris.read(buf)        
    }
    return new String(sb)
  }

  def doGetPATH(buf: String): String = {
    val Parts = buf.split("\n").filter(x => x.startsWith("GET "))
    Parts.length > 0 match {
      case true => (Parts(0).split("\\s+"))(1);
      case false => ""
    }
  } 

  def flow( is: InputStream , os: OutputStream): unit =   {
    var buf = new Array[byte](4*1024)
    var numRead: Int = is.read(buf)
    while ( numRead  >= 0) {
      os.write(buf, 0, numRead)
      numRead = is.read(buf)
    }
  }  
    



  def dirList(loc: String, rows: String): String = 
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" +  
"<html>" +
"<head>\n" +
"<title>Index of " + loc + "</title>\n" +
"<style type=\"text/css\">\n" +
"a, a:active {text-decoration: none; color: blue;}\n" +
"a:visited {color: #48468F;}\n" +
"a:hover, a:focus {text-decoration: underline; color: red;}\n" +
"body {background-color: #F5F5F5;}\n" +
"h2 {margin-bottom: 12px;}\n" +
"table {margin-left: 12px;}\n" +
"th, td { font: 90% monospace; text-align: left;}\n" +
"th { font-weight: bold; padding-right: 14px; padding-bottom: 3px;}\n" +
"td {padding-right: 14px;}\n" +
"td.s, th.s {text-align: right;}\n" +
"div.list { background-color: white; border-top: 1px solid #646464; border-bottom: 1px solid #646464; padding-top: 10px; padding-bottom: 14px;}\n" +
"div.foot { font: 90% monospace; color: #787878; padding-top: 4px;}\n" +
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<h2>Index of " +  loc +"</h2>\n" +
"<div class=\"list\">\n" +
"<table summary=\"Directory Listing\" cellpadding=\"0\" cellspacing=\"0\">\n" +
"<thead><tr><th class=\"n\">Name</th><th class=\"m\">Last Modified</th><th class=\"s\">Size</th><th class=\"t\">Type</th></tr></thead>\n" +
"\n" +
"<tbody>\n" +
"<tr><td class=\"n\"><a href=\"../\">Parent Directory</a>/</td><td class=\"m\">&nbsp;</td><td class=\"s\">- &nbsp;</td><td class=\"t\">Directory</td></tr>\n" +
"\n" + 
"\n" + rows +
"</tbody>\n" +
"</table>\n" +
"</div>\n" +
"<div class=\"foot\">ScalaServer/0.1 2008</div>\n" +
"</body>\n" +
"</html>\n"  






/*
  def main(args: Array[String]): unit = {
    val h = header("200 OK", 1024, "text/plain")
    println(h);

    h.split("\n").foreach(println)
    println(doGetPATH(h))
  }
*/
}

